<template>
  <div class="panel">
    <panel-title title="修改/新增规则"></panel-title>
    <div class="panel-body">
      <el-form :model="formData" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="规则名称" prop="description" :rules="{required: true, message: '请输入规则名称', trigger: 'blur'}">
          <el-input v-model="formData.description" label-width="100px" class="inputClass"></el-input>
        </el-form-item>
        <div v-for="(andCondition,outerIndex) in consJson">
          <el-form-item
            :key="'outer'+outerIndex"
            :label="'筛选条件' + outerIndex"
            label-width="100px">
            <div v-for="(orCondition,innerIndex) in andCondition" class="orConditionClass">
              <el-select
                v-model="orCondition.attrs[0].attrName"
                placeholder="请选择"
                style="width: 140px"
                :key="'innerAttr'+innerIndex"
              >
                <el-option
                  v-for="item in attrNameOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-select
                v-model="orCondition.attrs[0].operator"
                placeholder="请选择"
                style="width: 100px"
                :key="'innerOpera'+innerIndex"
              >
                <el-option
                  v-for="item in operatorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-input
                v-model="orCondition.attrs[0].params[0]"
                placeholder="请输入内容"
                style="width: 150px"
                :key="'innerParams'+innerIndex"
              >
              </el-input>
              <el-button type="success" @click="addInnerCondition(outerIndex)">添加或者</el-button>
              <el-button type="danger" @click="removeInnerCondition(outerIndex,innerIndex)"
                         v-if="consJson[outerIndex].length>1">删除或者
              </el-button>
            </div>
          </el-form-item>

          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item>
              <el-button type="success" @click="addOuterCondition()">添加并且</el-button>
              <el-button type="danger" @click="removeOuterCondition(outerIndex)" v-if="consJson.length>1">删除并且
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-form-item
          label="预警门槛"
          prop="alterSill"
          :rules="[
            {required: true, message: '预警门槛不能为空'},
            {type: 'number', message: '预警门槛必须为数字值'}
          ]"
        >
          <el-input v-model.number="formData.alterSill" class="inputClass"></el-input>
        </el-form-item>

        <div v-for="(email,index) in formData.emails">
          <el-form-item :label="'预警对象'+index"
                        :key="email.key"
                        :prop="'emails.' + index + '.email'"
                        :rules="[
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                        ]"
          >
            <el-input v-model="email.email" class="inputClass"></el-input>
            <el-button type="success" icon="el-icon-plus" circle @click="addEmail()"></el-button>
            <el-button type="danger" icon="el-icon-minus" circle v-if="formData.emails.length>1"
                       @click="removeEmail(index)"></el-button>
          </el-form-item>
        </div>
        <el-form-item label="是否自动运行">
          <template>
            <el-radio v-model="ruleType" :label="2">是</el-radio>
            <el-radio v-model="ruleType" :label="1">否</el-radio>
          </template>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="validateFrom('ruleForm')">保存</el-button>
          <el-button @click="cancelSizer()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>
<script>
  import {panelTitle} from 'components'
  import {userUtil} from 'common/tools'

  export default {
    data() {
      return {
        operatorOptions: [{
          label: '=',
          value: '='
        }, {
          label: '>',
          value: '>'
        }, {
          label: '>=',
          value: '>='
        }, {
          label: '<',
          value: '<'
        }, {
          label: '<=',
          value: '<='
        }, {
          label: '!=',
          value: '!='
        }, {
          label: '包含',
          value: 'contains'
        }, {
          label: '不包含',
          value: 'exclusion'
        }],
        attrNameOptions: [
          {
            label: '商家名称',
            value: 'seller_name'
          },
          {
            label: '省份名称',
            value: 'province_name'
          },
          {
            label: '城市名称',
            value: 'city_name'
          }, {
            label: '区域',
            value: 'area_name'
          }, {
            label: '商圈',
            value: 'region'
          }, {
            label: '地址',
            value: 'address'
          },
          {
            label: '创建时间',
            value: 'create_time'
          },
          {
            label: '更新时间',
            value: 'update_time'
          }, {
            label: '评分',
            value: 'score'
          },
          {
            label: '监控版本',
            value: 'monitor_version'
          },
          {
            label: '一级类目',
            value: 'province_name'
          },
          {
            label: '二级类目',
            value: 'province_name'
          },
          {
            label: '差评数',
            value: 'bad_comments'
          },
          {
            label: '最高日销量',
            value: 'max_day_solds'
          },
          {
            label: '当日均价',
            value: 'yesterday_avg_price'
          },
          {
            label: '近七日均价',
            value: 'day7_avg_price'
          },
          {
            label: '历史均价',
            value: 'history_avg_price'
          },
          {
            label: '当日销量',
            value: 'yesterday_solds'
          },
          {
            label: '近七日均销量',
            value: 'day7_avg_solds'
          }],
        formData: {
          id: null,
          description: null,
          alterSill: '',
          emails: [{key: '', email: ''}],
        },
        ruleType: 2,
        consJson: [
          [{
            attrs: [{
              params: [""],
              runPeriod: {},
              table: "b_seller",
              attrName: "",
              operator: "",
              attrType: "cont-string"
            }]
          }]
        ],
      }
    },
    components: {
      panelTitle
    },
    created() {
      var id = this.$route.params.id
      if (id != null) {
        //获取数据
        this.getSizerById(id)
      }

    },
    computed: {
      alterSendEmail: function () {
        var emailString = "";
        var len = this.formData.emails.length;
        for (var i = 0; i < len - 1; i++) {
          emailString += this.formData.emails[i].email + ","
        }
        emailString += this.formData.emails[len - 1].email
        return emailString
      }
    },
    methods: {
      addOuterCondition() {
        this.consJson.push([{
          attrs: [{
            params: [""],
            runPeriod: {},
            table: "b_seller",
            attrName: "",
            operator: "",
            attrType: "cont-string"
          }]
        }])
      },
      removeOuterCondition(outerIndex) {
        if (outerIndex >= -1 && this.consJson.length > 1) {
          this.consJson.splice(outerIndex, 1)
        }
      },
      addInnerCondition(outerIndex) {
        this.consJson[outerIndex].push(
          {
            attrs: [{
              params: [""],
              runPeriod: {},
              table: "b_seller",
              attrName: "",
              operator: "",
              attrType: "cont-string"
            }]
          }
        )
      },
      removeInnerCondition(outerIndex, innerIndex) {
        if (innerIndex >= -1 && this.consJson[outerIndex].length > 1) {
          this.consJson[outerIndex].splice(innerIndex, 1)
        }
      },
      addEmail() {
        this.formData.emails.push({
          email: '',
          key: Date.now()
        })
      },
      removeEmail(index) {
        if (index >= -1 && this.formData.emails.length > 1) {
          this.formData.emails.splice(index, 1)
        }
      },
      validateFrom(formName) {
        this.$refs[formName].validate((valid) => {
          console.log(valid);
          if (valid) {
            this.submitSizer();
          } else {
            return false;
          }
        });
      },
      cancelSizer() {
        this.$router.push({name: 'sellerSizer', params: {statRuleType: 1}})
      },
      submitSizer() {

        if (this.formData.id != null) {
          //修改操作
          this.$fetch.apiSizer.updateSizer({
            //1标识商家筛选器
            id: this.formData.id,
            statRuleType: 1,
            ruleType: this.ruleType,
            description: this.formData.description,
            consJson: JSON.stringify(this.consJson),
            alterSill: this.formData.alterSill,
            alterSendEmail: this.alterSendEmail,
          }).then(({data: data}) => {
            if (data == 1) {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              //this.$router.push()
              this.$router.push({name: 'sellerSizer', params: {statRuleType: 1}})
            } else {
              this.$message.error('修改失败');
            }
          })
        } else {
          var loginInfo = userUtil.getLoginInfo();
          //保存操作
          this.$fetch.apiSizer.addSizer({
            //1标识商家筛选器
            statRuleType: 1,
            ruleType: this.ruleType,
            description: this.formData.description,
            consJson: JSON.stringify(this.consJson),
            alterSill: this.formData.alterSill,
            alterSendEmail: this.alterSendEmail,
            userId: loginInfo.userId,
            userName: loginInfo.name
          }).then(({data: data}) => {
            if (data == 1) {
              this.$message({
                message: '新增成功',
                type: 'success'
              });
              //this.$router.push()
              this.$router.push({name: 'sellerSizer', params: {statRuleType: 1}})
            } else {
              this.$message.error('新增失败');
            }
          })
        }
      },
      getSizerById(id) {
        this.$fetch.apiSizer.getSizerById({
          id: id,
        }).then(({data: data}) => {
          this.formData.id = data.id
          this.ruleType = data.ruleType
          this.formData.description = data.description
          this.consJson = JSON.parse(data.consJson)
          this.formData.alterSill = parseInt(data.alterSill)
          var emails = data.alterSendEmail.split(",")
          this.formData.emails = []
          for (var i = 0; i < emails.length; i++) {
            this.formData.emails.push({
              key: Date.now(),
              email: emails[i]
            })
          }
          if (this.formData.emails.length <= 0) {
            this.formData.emails.push({
              key: Date.now(),
              email: ""
            })
          }
        })
      }
    }
  }
</script>
<style>
  .inputClass {
    width: 400px;
  }

  .orConditionClass {
    margin-bottom: 15px;
  }
</style>
